import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:gameplay_flutter/lib_baseview/theme/jr.dart';
import 'package:gameplay_flutter/lib_runtime/extension/widget/widget_wrapper.dart';
import 'package:ones/ui.dart';
import '../../../generated/assets.dart';
import '../../../lib_baseview/root_page.dart';
import '../../../lib_baseview/utils/screen_utils.dart';
import '../../../lib_chat/chat/index.dart';
import '../../../lib_runtime/common/lanuage_util.dart';
import '../../../lib_runtime/logger.dart';
import '../../../resource/language/generated/l10n.dart';
import '../msg/room_msg.dart';
import 'item_style.dart';

typedef InputCallback = void Function(String input,
    {ItemStyle itemStyle, String? extra, RoomMsg? quoteMsg});

class MessageInputBar extends StatefulWidget {
  final InputCallback onInputFinish;
  final bool showEmoji;
  RoomMsg? quoteMsg;
  MessageInputBar(
      {super.key,
      required this.onInputFinish,
      this.showEmoji = false,
      this.quoteMsg});

  @override
  State<StatefulWidget> createState() => _MessageInputBar();
}

class _MessageInputBar extends State<MessageInputBar>
    with WidgetsBindingObserver {
  late TextEditingController _controller;
  late FocusNode _focusNode;

  bool _showEmoji = false;
  bool _showQuickMsg = false;

  double _sendButtonOpacity = 0.4; // 新增变量来控制透明度

  RoomMsg? quoteMsg;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    quoteMsg = widget.quoteMsg;
    // _showQuickMsg = GlobalConfig.settingsResp?.enableRoomQuickMsg ?? false;
    _showEmoji = widget.showEmoji;
    _controller = TextEditingController();
    _focusNode = FocusNode();
    _focusNode.addListener(() {
      if (_showEmoji && _focusNode.hasFocus) {
        setState(() {
          _showEmoji = false;
        });
      }
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance?.removeObserver(this);
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    EdgeInsets ins =
        MediaQuery.of(rootNavigatorState.currentContext!).viewInsets;
    if (_focusNode.hasFocus) {
      if (ins.bottom > 0) {
        ScreenUtils.ins.keyboardHeight =
            max(ScreenUtils.ins.keyboardHeight, ins.bottom);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    double bottomSafeAreaHeight = MediaQuery.of(context).padding.bottom;

    return Scaffold(
      backgroundColor: Colors.transparent,
      resizeToAvoidBottomInset: !_showEmoji,
      body: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          //上部透明区域
          Expanded(
              child: GestureDetector(
            onTapDown: (_) {
              Navigator.pop(context);
            },
            child: Container(
              color: Colors.transparent,
            ),
          )),

          Container(
            height: 56,
            width: ScreenUtils.ins.screenWidth,
            color: Colors.white,
            padding: const EdgeInsetsDirectional.only(start: 15, end: 15),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Container(
                    color: const Color(0xFFF2F2F2),
                    height: 30,
                    child: Row(
                      children: [
                        const SizedBox(width: 3),
                        Container(
                          width: 198,
                          // decoration: BoxDecoration(
                          //     border: Border.all(
                          //   width: 1,
                          //   color: Colors.red,
                          // )),
                          child: TextField(
                            // autofocus: true,
                            controller: _controller,
                            autofocus: !_showEmoji,
                            focusNode: _focusNode,
                            cursorHeight: 15,
                            cursorRadius: const Radius.circular(4),
                            maxLengthEnforcement: MaxLengthEnforcement.enforced,
                            inputFormatters: [
                              LengthLimitingTextInputFormatter(200)
                            ],
                            onTap: () {
                              // logic.hintText(T.current.say_something);
                              // logic.showEmojiView(false);
                              // logic.commentId = null;

                              print('输入内容发生变化，onTap：');
                            },
                            onChanged: (value) {
                              print('输入内容发生变化，当前内容为：$value');
                              setState(() {
                                _sendButtonOpacity =
                                    value.isNotEmpty ? 1.0 : 0.4;
                              });
                              // if (value.isNotEmpty) {
                              //   logic.sendEnable(true);
                              // } else {
                              //   logic.sendEnable(false);
                              // }
                              // if (value.isNotEmpty &&
                              //     value.length > logic.previewText.length &&
                              //     value.endsWith(' @')) {
                              //   logic.atUser();
                              // }
                              // logic.previewText = value;
                            },
                            onSubmitted: (value) {
                              print('用户提交输入，提交内容为：$value');
                              // logic.discoverComment();
                              // _sendMsg();
                            },
                            style: const TextStyle(
                              color: Color(0xffA5A1B9),
                              fontSize: 16,
                            ),
                            decoration: InputDecoration(
                              hintText: T.current.room17_say_something,
                              hintStyle: const TextStyle(
                                  color: Color(0xffA5A1B9), fontSize: 16),
                              border: InputBorder.none,
                              isCollapsed: true,
                              contentPadding:
                                  const EdgeInsetsDirectional.only(start: 13),
                            ),
                          ),
                        ),
                        Image.asset(Assets.discoverEmoji, width: 28, height: 28)
                            .onClick(
                          () {
                            _focusNode.unfocus();
                            setState(() {
                              _showEmoji = true;
                            });
                          },
                        ).marginRight(16),
                      ],
                    ),
                  ).corner(radius: 15),
                ),
                const SizedBox(width: 6),
                Opacity(
                  opacity: _sendButtonOpacity,
                  child: sendWidget,
                ).onClick(() {
                  _sendMsg();
                }),
              ],
            ),
          ),

          // Visibility(
          //   visible: logic.showEmojiView(),
          // child: MessageEmoji(
          //   onTap: (emoji) => logic.messageController.text += emoji,
          // ).height(320),
          // ),

          if (_showEmoji)
            Container(
              color: Colors.white,
              child: MessageEmoji(
                onTap: (emoji) {
                  setState(() {
                    _controller.text += emoji;
                    print('MessageInputBar showEmoji: ${_controller.text}');
                  });
                },
              ).height(300),
            ),

          Container(
            color: Colors.white,
            height: bottomSafeAreaHeight,
          ),
        ],
      ),
    );
  }

  Widget get sendWidget {
    // 创建发送文本 Widget
    Widget sendText = Text(T.current.send)
        .fontSize(16)
        .colorInt(0xffffffff)
        .fontWeight(FontWeight.w600);
    // 创建发送图标 Widget
    Widget sendIcon = JR.img(Assets.discoverPost, width: 18, height: 18);
    // 创建间隔 Widget
    Widget spacer = const SizedBox(width: 4);

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [sendText, spacer, sendIcon],
    )
        .paddingSymmetric(horizontal: 15, vertical: 7)
        .backgroundColorInt(0xff8A72FE)
        .roundedRect(90);
  }

  /// 外部表情
  _sendOutSideEmote(String desc, String resource) {
    // if (UserManager.instance.currentUser?.superAdmin ?? false) {
    //   showToast(T.current!.cant_send);
    //   return;
    // }
    Map<String, dynamic> extra = {
      'type': 'emote',
      'emote': {'emoticons_id': -2, 'desc': desc, 'url': resource}
    };
    widget.onInputFinish(desc,
        itemStyle: ItemStyle.text,
        extra: json.encode(extra),
        quoteMsg: quoteMsg);
    Navigator.pop(context);
  }

  void _sendMsg({String? msg}) {
    var inputText = msg ?? _controller.text.trim();
    if (inputText.isEmpty) {
      return;
    }
    // if (UserManager.instance.currentUser?.superAdmin ?? false) {
    //   showToast(T.current!.cant_send);
    //   return;
    // }
    widget.onInputFinish(inputText, quoteMsg: quoteMsg);
    _controller.text = "";
    Navigator.pop(context);
  }

  log(String s) {
    RLog.d(s, "MessageInputBar");
  }
}
